<?php
// Debug output functionality.
// derr() outputs to error.log, dwarn() outputs to warning.log, dinfo() outputs to info.log
// Dependencies: None
// Part of mmvc library, https://code.google.com/p/mmvc/
// Assumes define DEBUG_LOG_PATH is set

if ( !defined('DEBUG_LOG_PATH') ) {
	if ( defined('ROOTPATH') )
		define( 'DEBUG_LOG_PATH', ROOTPATH.'log/' );
	else
		define( 'DEBUG_LOG_PATH', './log/' );
}

if ( !defined('DEBUG_LEVEL') ) {
	define( 'DEBUG_LEVEL', 3 ); // 1=err, 2=warn, 3=info
}

/** 
 * Debug printf to log file. On command line invocation prints log entry to console as well.
 * @param $level Debug level string ('error', 'warning', 'info')
 * @param $a Array: Message format followed by arguments, e.g. array("123=%d\n",123).
 * @return false
 */
function dvprintf( $level, $args, $trace=false ) {
	$msg = sizeof($args)==1 ? $args[0] : vsprintf($args[0],array_slice($args,1));
	$str = date('Y-m-d H:i:s ').rtrim($msg)."\n".($trace?$trace."\n":'');
	@file_put_contents( DEBUG_LOG_PATH.$level.'.log', $str, FILE_APPEND );
	if (PHP_SAPI === 'cli') {echo $str;}
	return false;
}

/** Returns debug stack trace as string. */
function dtrace()	{try {throw new Exception();} catch (Exception $e) {return $e->getTraceAsString();} return '';}

/** Printf error to debug log. Usage example: derr("Hello, 123=%d\n",123). */
function derr()		{if (DEBUG_LEVEL >= 1) return dvprintf('error',func_get_args(),dtrace());}

/** Printf warning to debug log. Usage example: dwarn("Hello, 123=%d\n",123). */
function dwarn()	{if (DEBUG_LEVEL >= 2) return dvprintf('warning',func_get_args());}

/** Printf informative notice to debug log. Usage example: dinfo("Hello, 123=%d\n",123). */
function dinfo()	{if (DEBUG_LEVEL >= 3) return dvprintf('info',func_get_args());}
